package com.jilian.mydemo.modul.shop.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.base.CommonViewPagerAdapter;
import com.jilian.mydemo.common.dto.ProductDetailDto;
import com.jilian.mydemo.common.dto.SelectGoodDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.views.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

public class GoodDetailActivity extends BaseActivity {
    private List<Fragment> mFragmentList;
    private GoodsDetailLeftFragment leftFragment;
    private GoodsDetailCenterFragment centerFragment;
    private CommonViewPagerAdapter adapter;
    private NoScrollViewPager customScrollViewPager;
    public TextView tvLeft;
    public TextView tvCenter;
    public RelativeLayout rlLeft;
    public RelativeLayout rlCenter;
    private TextView tvJoinShopCart;
    private TextView tvBuy;

    private LinearLayout llShop;
    private LinearLayout llBottom;
    private UserViewModel viewModel;
    private OrderViewModel orderViewModel;
    private TextView tvCount;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        if (savedInstanceState != null) {
            savedInstanceState.remove("android:support:fragments");
            //注意：基类是Activity时参数为android:fragments， 一定要在super.onCreate函数前执行！！！
        }
        super.onCreate(savedInstanceState);

        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_gooddetail;
    }

    @Override
    public void initView() {
        setNormalTitle("商品信息", v -> finish());
        customScrollViewPager = (NoScrollViewPager) findViewById(R.id.customScrollViewPager);
        tvLeft = (TextView) findViewById(R.id.tv_left);
        tvCenter = (TextView) findViewById(R.id.tv_center);
        rlLeft = (RelativeLayout) findViewById(R.id.rl_left);
        rlCenter = (RelativeLayout) findViewById(R.id.rl_center);
        tvJoinShopCart = (TextView) findViewById(R.id.tv_joinShopCart);
        tvBuy = (TextView) findViewById(R.id.tv_buy);
        llShop = (LinearLayout) findViewById(R.id.ll_shop);
        llBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        tvCount = (TextView) findViewById(R.id.tv_count);

    }

    @Override
    public void initData() {
        mFragmentList = new ArrayList<>();
        leftFragment = new GoodsDetailLeftFragment();
        centerFragment = new GoodsDetailCenterFragment();
        mFragmentList.add(leftFragment);
        mFragmentList.add(centerFragment);
        adapter = new CommonViewPagerAdapter(getSupportFragmentManager(), mFragmentList);
        customScrollViewPager.setAdapter(adapter);
        //    //1 首頁進來 //2 为添加配件 跳到 该界面
        if (getIntent().getIntExtra("param", 1) == 1) {
            llBottom.setVisibility(View.GONE);
        } else {
            llBottom.setVisibility(View.VISIBLE);
        }
        getDetailData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getShopCarData();
    }

    /**
     * 获取购物车数量
     */
    private void getShopCarData() {
        orderViewModel.getShoppingCartProducts();
        orderViewModel.getShopListliveData().observe(this, new Observer<BaseDto<List<ProductDetailDto>>>() {
            @Override
            public void onChanged(@Nullable BaseDto<List<ProductDetailDto>> shopListDtoBaseDto) {
                hideLoadingDialog();
                if (shopListDtoBaseDto.isSuccess())
                {
                    if (EmptyUtils.isNotEmpty(shopListDtoBaseDto)
                            && EmptyUtils.isNotEmpty(shopListDtoBaseDto.getData())) {
                        tvCount.setVisibility(View.VISIBLE);
                        tvCount.setText(shopListDtoBaseDto.getData().size() + "");
                    }
                    else{
                        tvCount.setVisibility(View.GONE);
                    }
                } else {
                    ToastUitl.showImageToastTips(shopListDtoBaseDto.getMsg());
                    tvCount.setVisibility(View.GONE);
                }
            }
        });
    }

    private ProductDetailDto detailDto;

    private void getDetailData() {
        showLoadingDialog();
        Long id = Long.parseLong(getIntent().getStringExtra("id"));
        viewModel.getAppProductDetail(id);
        viewModel.getDetailliveData().observe(this, new Observer<BaseDto<ProductDetailDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<ProductDetailDto> dto) {
                hideLoadingDialog();
                if (dto.isSuccess()) {
                    if (dto.getData() != null) {
                        detailDto = dto.getData();
                        BaseEventMsg eventMsg = new BaseEventMsg();
                        eventMsg.setProductDetailDto(detailDto);
                        RxBus.getInstance().post(eventMsg);
                    }

                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    @Override
    public void initListener() {
        tvLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customScrollViewPager.setCurrentItem(0);
                rlLeft.setVisibility(View.VISIBLE);
                tvLeft.setTextColor(getResources().getColor(R.color.color_main_title));

                rlCenter.setVisibility(View.INVISIBLE);
                tvCenter.setTextColor(getResources().getColor(R.color.color_hint));


            }
        });

        tvCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customScrollViewPager.setCurrentItem(1);
                rlCenter.setVisibility(View.VISIBLE);
                tvCenter.setTextColor(getResources().getColor(R.color.color_main_title));

                rlLeft.setVisibility(View.INVISIBLE);
                tvLeft.setTextColor(getResources().getColor(R.color.color_hint));

            }
        });
        tvJoinShopCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(GoodDetailActivity.this, InputDataActivity.class);
//                startActivity(intent);
                showMyDialog(1);

            }
        });
        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMyDialog(2);
//                Intent intent = new Intent(GoodDetailActivity.this, InputDataActivity.class);
//                startActivity(intent);
            }
        });
        llShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(GoodDetailActivity.this, ShoppingCartActivity.class));
            }
        });
    }

    /**
     * 购买。添加购物车对话框
     *
     * @param type 1.加入购物车  2.购买
     */
    private void showMyDialog(int type) {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_buy_good)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);

                        TextView tvCancel = (TextView) holder.getView((R.id.tv_cancel));
                        TextView tvOk = (TextView) holder.getView((R.id.tv_ok));
                        EditText etPrice = (EditText) holder.getView(R.id.et_price);

                        etPrice.setText(detailDto.getPrice());

                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        tvOk.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (TextUtils.isEmpty(etPrice.getText().toString())) {
                                    return;
                                }
                                dialog.dismiss();

                                if (type == 1) {
                                    addShop(etPrice.getText().toString());
                                }
                                if (type == 2) {
                                    buy(etPrice.getText().toString());
                                }

                            }
                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    /**
     * 添加到购物车
     *
     * @param pric
     */
    private void addShop(String pric) {
        showLoadingDialog();
        orderViewModel.addProductToShoppingCart(String.valueOf(detailDto.getId()), String.valueOf(leftFragment.getCount()), pric);
        orderViewModel.getAddShopliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto baseDto) {
                hideLoadingDialog();
                if (baseDto.isSuccess()) {
                    ToastUitl.showImageToastSuccess("添加成功");
                    getShopCarData();
                } else {
                    ToastUitl.showImageToastTips(baseDto.getMsg());
                }
            }
        });

    }

    /**
     * 添加到订单
     *
     * @param pric
     */
    private void buy(String pric) {
        //选择的配件商品信息
        SelectGoodDto selectGoodDto = new SelectGoodDto();
        List<ProductDetailDto> detailDtoList = new ArrayList<>();
        detailDto.setQuantity(String.valueOf(leftFragment.getCount()));
        detailDto.setActualPrice(pric);
        detailDtoList.add(detailDto);
        selectGoodDto.setDetailDtoList(detailDtoList);
        //通知刷新那
        BaseEventMsg eventMsg = new BaseEventMsg();
        eventMsg.setSelectGoodDto(selectGoodDto);
        RxBus.getInstance().post(eventMsg);
        MyApplication.clearSpecifyActivities(new Class[]{AccessoriesShopActivity.class});
        finish();
    }


}
